// pages/productList/productList.js
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    products: [],
    pageNum: 1,
    pageSize: 12,
    hasMore: true,
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getProducts();
  },

  /**
   * 获取商品列表
   */
  getProducts() {
    if (this.data.loading || !this.data.hasMore) {
      return;
    }

    this.setData({ loading: true });

    wx.request({
      url: `${app.globalData.baseUrl}/product/list?pageNum=${this.data.pageNum}&pageSize=${this.data.pageSize}`,
      method: 'GET',
      success: (res) => {
        console.log('商品列表数据', res.data);
        const newProducts = res.data.rows || [];
        const products = this.data.pageNum === 1 ? newProducts : [...this.data.products, ...newProducts];
        const hasMore = newProducts.length === this.data.pageSize;

        this.setData({
          products: products,
          hasMore: hasMore,
          loading: false
        });
      },
      fail: (err) => {
        console.error('获取商品列表失败', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  /**
   * 点击商品项
   */
  onProductTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/details/details?productId=${id}`,
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        pageNum: this.data.pageNum + 1
      });
      this.getProducts();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      pageNum: 1,
      hasMore: true,
      products: []
    });
    this.getProducts();
    wx.stopPullDownRefresh();
  }
})